<template>
  <div class="region-index">
    <tx-block>
      <div v-if="!$currentUserInfo">
        <tx-button-add name="新增指挥体系" @click="add" />
      </div>
      <div
        v-else
        style="
          padding-bottom: 10px;
          display: flex;
          align-items: center;
          color: #fff;
        "
      >
        <span style="flex: 1">当前位置：{{ this.stepsLocationName }}</span>
        <div class="btnbox-right">
          <tx-button-add icon="" name="返回上一级" @click="handlePreLevel" />
        </div>
      </div>
      <el-form ref="form" :model="form" label-width="0px">
        <tx-list-table
          :table="table"
          ref="listTable"
          row-key="name"
          v-loading="table.loading"
        >
          <tx-table-column-text label="排序" width="60">
            <template slot-scope="scope"
              ><span class="number-index">{{
                scope.scope.scope.$index + 1
              }}</span></template
            >
          </tx-table-column-text>
          <tx-table-column-text :label="$dictValue('{name}名称')">
            <template slot-scope="scope">
              <span v-if="scope.row.createType == 1">{{
                scope.row.orgName
              }}</span>
              <tx-table-input
                v-else
                :entity="scope.row"
                name="orgName"
                :action="scope.row?.$action"
                :rules="formRules.orgName"
                :prop="buildRowProp(scope, 'orgName')"
                placeholder="请输入指挥体系名称"
              />
            </template>
          </tx-table-column-text>
          <tx-table-column-text label="管理员姓名">
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                name="name"
                :action="scope.row?.$action"
                :rules="formRules.name"
                :prop="buildRowProp(scope, 'name')"
                placeholder="请输入管理员姓名"
              />
            </template>
          </tx-table-column-text>
          <tx-table-column-text
            label="管理员所在单位"
            width="180"
            v-if="menuId != '1000000005'"
          >
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                name="workUnit"
                :action="scope.row.$action"
                :rules="formRules.workUnit"
                :prop="buildRowProp(scope, 'workUnit')"
                placeholder="请输入管理员所在单位"
              />
            </template>
          </tx-table-column-text>
          <tx-table-column-text label="管理员所在内设机构">
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                name="office"
                :action="scope.row.$action"
                :rules="formRules.office"
                :prop="buildRowProp(scope, 'office')"
                placeholder="请输入管理员所在内设机构"
              />
            </template>
          </tx-table-column-text>
          <tx-table-column-text label="管理员职务">
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                name="job"
                :action="scope.row.$action"
                :rules="formRules.job"
                :prop="buildRowProp(scope, 'job')"
                placeholder="请输入管理员职务"
              />
            </template>
          </tx-table-column-text>
          <tx-table-column-text label="管理员手机号">
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                name="phone"
                :action="scope.row.$action"
                :rules="formRules.phone"
                :prop="buildRowProp(scope, 'phone')"
                placeholder="请输入管理员手机号"
              />
            </template>
          </tx-table-column-text>
          <tx-table-column-action align="left" :key="$columnKey()" width="230">
            <template slot-scope="scope">
              <el-form
                :ref="`form${scope.scope.scope.$index}`"
                :model="form.record"
                :rules="formRules"
                style="display: none"
              >
                <tx-form-input :entity="form.record" name="orgName" />
                <tx-form-input :entity="form.record" name="name" />
                <tx-form-input
                  :entity="form.record"
                  name="workUnit"
                  v-if="menuId != '1000000005'"
                />
                <tx-form-input :entity="form.record" name="office" />
                <tx-form-input :entity="form.record" name="job" />
                <tx-form-input :entity="form.record" name="phone" />
              </el-form>
              <!-- <tx-link text="编辑" name="dept" :query="{itemId: scope.row.itemId}"  />
                        <tx-link text="删除" name="dept" :query="{itemId: scope.row.itemId}"  />  -->
              <el-button
                type="primary"
                size="mini"
                v-if="scope.row.$action != 'modify'&& !$currentUserInfo"
                class="table-edit-btn"
                @click="handleEdit(scope)"
                >编辑
              </el-button>
              <el-button
                type="primary"
                size="mini"
                v-if="scope.row.id && scope.row.$action != 'modify'"
                class="table-edit-btn"
                @click="handleLevelDetail(scope)"
                >详情
              </el-button>
              <el-button
                type="primary"
                size="mini"
                v-if="scope.row.$action == 'modify'"
                @click="handleSave(scope)"
                class="table-save-btn"
                v-preventReClick="3000"
                >保存
              </el-button>
              <el-button
                size="mini"
                type="warning"
                v-if="scope.row.$action == 'modify'"
                @click="handleCancel(scope)"
                class="table-cancel-btn"
                >取消
              </el-button>
              <!-- // 编辑状态 + 不是当前登录人手机号 + createType=2  -->
              <tx-button-text-delete
                class="table-del-btn"
                v-if="
                  (scope.row.$action == 'modify' &&
                    !disabledEdit(scope.row.phone) &&
                    scope.row.createType == 2) ||
                  !scope.row.orgId
                "
                controller="OrgController"
                :body="scope.row"
                :idValue="scope.row.id"
                :success="$handleQuery"
                target="记录"
              />
            </template>
          </tx-table-column-action>
        </tx-list-table>
      </el-form>
    </tx-block>
    <validate-phone
      @success="SubmitEvent"
      :form="form.record"
      ref="validatePhone"
    ></validate-phone>
  </div>
</template>

<script>
import TxTableInput from "@/components/tx/tx-form/TxTableInput.vue";

export default {
  components: { TxTableInput },
  name: "Login",
  data() {
    return {
      menuID: "",
      table: {
        loading: false,
        query: {},
        sort: {
          descs: ["updateTime"],
        },
        page: this.$yzvue.initPage(),
      },
      dict: {
        name: "指挥体系",
      },
      form: {
        new: {
          orgName: "",
          name: "",
          workUnit: "",
          office: "",
          job: "",
          phone: "",
        },
        record: {
          orgName: "",
          name: "",
          workUnit: "",
          office: "",
          job: "",
          phone: "",
        },
        records: [],
      },
      formRules: {
        orgName: this.$rule.name("指挥体系名称", null, 32),
        name: this.$rule.name("姓名", null, 32),
        workUnit: this.$rule.name("单位", null, 32),
        office: this.$rule.name("机构", null, 32),
        job: this.$rule.name("职务", null, 32),
        phone: this.$rule.mobile("手机号", true),
      },
    };
  },
  computed: {
    menuId() {
      return this.getParameter("menuId");
    },
    disabledEdit() {
      return function (phone) {
        return (
          this.$userInfo.phone == phone &&
          ["1000000007", "1000000015", "1000000016"].includes(
            this.getParameter("menuId")
          )
        );
      };
    },
  },
  mounted() {
    this.loadTable();
    this.menuID = this.$userInfo.menuID;
  },
  methods: {
    handleQuery() {
      this.loadTable();
    },
    loadTable() {
      let param = this.$handleQueryParam();
      param.body.createdBy =
        this.$currentUserInfo?.phone || this.$userInfo.phone;
      param.body.orgId = this.$currentUserInfo?.orgId || this.$userInfo.orgId;
      console.log(param);
      this.table.loading = true;
      this.$api.DeptController.list(param, (res) => {
        this.table.loading = false;
        console.log(res);
        for (let ri = 0; ri < res.data.length; ri++) {
          const re = res.data[ri];
          re.$action = "view";
        }
        this.$yzvue.assembleBody(this.table.page, { records: res.data });
        this.form.records = res.data;
      });
    },
    buildRowProp($scope, field) {
      let {
        scope: { scope },
      } = $scope;
      return `records.${scope.$index}.${field}`;
    },
    // 编辑
    handleEdit($scope) {
      $scope.row.$action = "modify";
      let { orgName, name, workUnit, office, job, phone } = $scope.row;
      $scope.row.$origin = { orgName, name, workUnit, office, job, phone };
    },
    add() {
      this.$nextTick(() => {
        window.scrollTo(0, this.$el.ownerDocument.body.scrollHeight);
        // this.$el.ownerDocument.scrollTo({top: 100, behavior: "smooth"})
      });
      Object.keys(this.form.record).forEach((v) => {
        this.form.record[v] = "";
      });
      let newRow = this.$lodash.cloneDeep({
        ...this.form.record,
        $action: "modify",
      });
      this.table.page.records.push(newRow);
    },

    // 保存
    handleSave($scope) {
      Object.assign(this.form.record, $scope?.row || {});
      let { id, phone } = this.form.record;
      this.$handleFormValidate(`form${$scope.scope.scope.$index}`, async () => {
        if (($scope.row.id && $scope.row.$origin.phone != phone) || !$scope.row.id) {
          //新增或者编辑状态下有修改手机号，则弹窗校验手机号
          let res = await this.$existAd(id, phone);
          if (res?.data) {
            this.$refs.validatePhone.init();
            return false;
          }
        } 
        this.SubmitEvent(); 
      });
    },
    //数据提交
    SubmitEvent() {
      let { id, orgName, name, workUnit, office, job, phone, areaCode } =
        this.form.record;
      let isModify = id;
      let pack = {};
      if (isModify) {
        //   pack.body={ id, orgName, name, workUnit, office, job, phone  }
        pack.body = {
          id,
          orgName,
          name,
          office,
          job,
          phone,
          workUnit,
          areaCode,
        };
      } else {
        pack.body = {
          // id, orgName, name, workUnit, office, job, phone ,
          id,
          orgName,
          name,
          office,
          job,
          phone,
          workUnit,
          menuID: this.getParameter("menuId"),
          areaCode,
          createdBy: this.$userInfo.phone,
        };
      }
      this.table.loading = true;
      let newMethod = this.$api.AdminController.new;
      let updateMethod = this.$api.AdminController.update;
      this.$invokeSave(pack, "id", newMethod, updateMethod, (res) => {
        this.table.loading = false;
        if (res && res.data) {
          this.form.record.$action = "view";
          // if (!isModify) {
          //   $scope.row.id = res.data;
          // }
          this.loadTable();
        }
      });
    },
    // 取消
    handleCancel($scope) {
      Object.assign($scope.row, $scope.row.$origin);
      $scope.row.$action = "view";
      this.$refs["form"].clearValidate();
    },
  },
};
</script>

<style lang="scss">
.main-container .region-index {
  .tx-list-query {
    margin: 0px;

    // border: 2px solid $c-bd-menu;
  }
  .tx-block {
    width: auto;
    margin: 0px 0px;
    padding: 0 15px;
    background-color: $c-bg-query;
    border: 1px solid $c-bd-content;
    .tx-block--content {
    }
  }

  .el-table td.el-table__cell {
    padding: 8px 0px 0px 0px;
    .cell > span {
      display: block;
      padding-bottom: 13px;
      line-height: 30px;
    }
    .tx-table-column-action {
      display: block;
      padding-bottom: 10px;
    }

    .el-input__inner {
      height: 30px;
      line-height: 30px;
      padding: 0px 5px;
    }
    .el-form-item {
      margin-bottom: 13px;
    }
    .el-form-item__content {
      line-height: 30px;
    }
    .el-form-item__error {
      padding-top: 0px;
    }
  }
}
</style>
